/*
 * @Author: yx_ning
 * @Description:
 * @File: login
 * @Version: 1.0.0
 * @Date: 22/12/2023 下午2:07
 */
package user

import (
	"errors"
	"fmt"
	"gin-simple/global"
	"gin-simple/model"
	"gin-simple/model/req"
	"gin-simple/model/resp"
	"gin-simple/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type LoginApi struct {
}

func (login *LoginApi) Login(c *gin.Context) {
	var params req.Login
	err := c.ShouldBindJSON(&params)
	fmt.Println(params)
	errMsg := utils.CommonVerify(params, err)
	if errMsg != "" {
		resp.FailWithMessage(errMsg, c)
		return
	}

	var user *model.User
	err = global.DB.Where("phone = ? and password = ?", params.Phone, params.Password).First(&user).Error

	if errors.Is(err, gorm.ErrRecordNotFound) {
		resp.FailWithMessage("账户或密码错误", c)
		return
	}
	login.TokenNext(c, *user)
}

// TokenNext 登录以后签发jwt
func (login *LoginApi) TokenNext(c *gin.Context, user model.User) {
	j := &utils.JWT{SigningKey: []byte(global.CONFIG.JWT.SigningKey)} // 唯一签名
	claims := j.CreateClaims(req.BaseClaims{
		ID:       user.ID,
		NickName: user.NickName,
		Username: user.UserName,
	})
	token, err := j.CreateToken(claims)
	if err != nil {
		global.LOG.Error("获取token失败!", zap.Error(err))
		resp.FailWithMessage("获取token失败", c)
		return
	}

	resp.OkWithDetailed(resp.LoginResp{
		User:      user,
		Token:     token,
		ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
	}, "登录成功", c)
}

func (login LoginApi) GetUserInfo(c *gin.Context) {
	uid := utils.GetUserID(c)
	var user *model.User
	global.DB.Where("id = ?", uid).Find(&user)

	resp.OkWithData(user, c)
}
